package top.itaso.lib.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.view.ViewTreeObserver;

/**
 * @Description: 下载进度条/上传进度条 等
 * @Author itsdf07
 * @E-Mail 923255742@qq.com
 * @Gitee https://gitee.com/itsdf07
 * @Date 2022/4/3
 */
public class DownloadProgressBarView1 extends View {
    private final String TAG = this.getClass().getSimpleName();
    /**
     * 绘制ProgressBar的线条（包含底色和进度）画笔
     */
    private Paint mPaintProgressBar = new Paint();
    private Paint mPaintPercentText = new Paint();
    private float mOffset = 0f; // 下载偏移量
    /**
     * 下载的文件总大小，单位：字节（B）
     */
    private float mMaxValue = 0f;
    /**
     * 当前已下载的大小，单位：字节（B）
     */
    private float mDownloadValue = 0f;
    // 用于 Paint.getTextBounds(String text, int start, int end, Rect bounds)之后使用Rect.width 获取百分比数字的长宽
    private Rect mBound = new Rect();
    private String mPercentValue = "0%"; // 要显示的现在百分比
    /**
     * 已下载进度值字体大小，一般是百分比的值，如 77
     */
    private int mDownloadValueTextSize;
    /**
     * 已下载进度值字体颜色
     */
    private int mDownloadValueForegrond;
    /**
     * 已下载进度值字体背景色
     */
    private int mDownloadValueBackgrond;
    /**
     * 轨道的颜色(不会动的进度条底部部分)
     */
    private int mTrackBackgrond;
    /**
     * 完成部分的颜色(时刻变化着的实际下载的进度条部分)
     */
    private int mThumbBackgrond;

    private float mOffsetRight = 0f; // 灰色线条距离右边的距离
    private float mOffsetTop = 18f; // 距离顶部的偏移量

    public DownloadProgressBarView1(Context context) {
        this(context, null);
    }

    public DownloadProgressBarView1(Context context, AttributeSet attribute) {
        this(context, attribute, 0);
    }

    public DownloadProgressBarView1(Context context, AttributeSet attrs,
                                    int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        TypedArray t = getContext().obtainStyledAttributes(attrs, R.styleable.downloadProgressBar);
        mDownloadValueTextSize = (int) t.getDimension(R.styleable.downloadProgressBar_textsize_download_value, 42);
        mDownloadValueForegrond = t.getColor(R.styleable.downloadProgressBar_fg_download_value, getResources().getColor(R.color.color_1671d9));
        mDownloadValueBackgrond = t.getColor(R.styleable.downloadProgressBar_bg_download_value, getResources().getColor(R.color.white));
        mTrackBackgrond = t.getColor(R.styleable.downloadProgressBar_bg_full_progressbar, getResources().getColor(R.color.color_B5B5B5));
        mThumbBackgrond = t.getColor(R.styleable.downloadProgressBar_bg_download_progressbar, getResources().getColor(R.color.color_1671d9));

        mOffsetRight = measureTextWidth("100%");
        Log.d(TAG, "DownloadProgressBarView1: >>>>>>mPercentTextSize:" + mDownloadValueTextSize + ",mOffsetRight:" + mOffsetRight);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        // 绘制轨道 track 部分-绘制底色(不会动的进度条底部部分)
        mPaintProgressBar.setColor(mTrackBackgrond);
        mPaintProgressBar.setStrokeWidth(2);//画笔设置粗细
        canvas.drawLine(0, mOffsetTop, getWidth(), mOffsetTop, mPaintProgressBar);

        // 绘制已完成进度 thumb 部分-已完成部分颜色(时刻变化着的实际下载的进度条部分)
        mPaintProgressBar.setColor(mThumbBackgrond);
        mPaintProgressBar.setStrokeWidth(4);
        canvas.drawLine(0, mOffsetTop, mOffset, mOffsetTop, mPaintProgressBar);

        // 绘制白色区域及百分比(即百分比文案下的底色，用于抹掉底色呈现在进度值上，使其有种断层的视觉效果，一般跟背景色一致)
        mPaintProgressBar.setColor(mDownloadValueBackgrond);
        mPaintProgressBar.setStrokeWidth(2);

        //绘制进度条上的百分比文案
        mPaintPercentText.setColor(mDownloadValueForegrond);
        mPaintPercentText.setTextSize(mDownloadValueTextSize);
        mPaintPercentText.setAntiAlias(true);
        mPaintPercentText.getTextBounds(mPercentValue, 0, mPercentValue.length(), mBound);
        canvas.drawLine(mOffset, mOffsetTop, mOffset + mBound.width() + 4, mOffsetTop, mPaintProgressBar);
        Log.v(TAG, "onDraw: >>>>>>offsetTop:" + mOffsetTop + ",offset:" + mOffset + ",percentValue:" + mPercentValue);

        //不能早于 mPaintPercentText.getTextBounds ，否则此时的 mBound 尚且无法计算出 百分比 的宽度，比如刚开始时的 0%
        canvas.drawText(mPercentValue, mOffset, mOffsetTop + mBound.height() / 2 - 2, mPaintPercentText);
    }

    /**
     * 设置下载内容总大小
     *
     * @param maxValue 下载内容的总大小，单位：字节（B）
     */
    public void setMaxValue(float maxValue) {
        this.mMaxValue = maxValue;
    }

    /**
     * 设置当前进度值，先设置 setMaxValue 之后，内部自动转成 [0-100] 闭区间的百分比
     *
     * @param curValue 当前已下载的大小，单位：字节（B）
     */
    public void setCurrentValue(float curValue) {
        this.mDownloadValue = curValue;
        int value = (int) (this.mDownloadValue / mMaxValue * 100);
        if (value < 100) {
            mPercentValue = value + "%";
        } else {
            mPercentValue = "100%";
        }
        initCurrentProgressBar();
        invalidate();
    }

    /**
     * 获取当前进度条长度
     *
     * @return
     */
    private void initCurrentProgressBar() {
        getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {

            @Override
            public void onGlobalLayout() {
                if (mDownloadValue < mMaxValue) {
                    mOffset = (getWidth() - mOffsetRight) * (mDownloadValue / mMaxValue);
                } else {
                    mOffset = getWidth() - mOffsetRight;
                }
                Log.v(TAG, "onGlobalLayout: >>>>>>mDownloadValue:" + mDownloadValue + ",offset:" + mOffset);
            }
        });

    }

    /**
     * 计算画笔绘制指定的字符串宽度
     *
     * @param percentValue 如 100% 、 0%
     * @return
     */
    private int measureTextWidth(String percentValue) {
        Paint paint = new Paint();
        Rect rect = new Rect();
        paint.setTextSize(mDownloadValueTextSize);
        paint.setAntiAlias(true);
        paint.getTextBounds(percentValue, 0, percentValue.length(), rect);
        return rect.width() + 5;
    }
}
